package cn.crex1.xiaomi.core.mvc.util;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Properties;
import cn.crex1.xiaomi.core.mvc.context.ContextLoader;

public class PropertiesUtil {
	
	private static final String empty = "";
	
	private static final String path="/";

	private static final String resource="resource.properties";
	
	private static final String mvcproperties="mvc.properties";
	
	private static final String webcontext="webcontext";
	
	private static final String scan_basepackage="scan-basepackage";
	
	public static URI localClassPath(Class<?> clazz,String pathflag) {
		URI uri = null;
		try {
			uri = clazz.getResource(pathflag).toURI();
			System.out.println(uri);
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return uri;
	}
	
	public static Properties loadPropertiesResource(Class<?> clazz) {
		Properties p=new Properties();
		if (clazz.equals(ContextLoader.class)) {
			Path parent = Paths.get(localClassPath(clazz,empty)).getParent();
			try {
				p.load(Files.newInputStream(Paths.get(parent.toString()+File.separator+resource),StandardOpenOption.READ));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (clazz.equals(ContextLoader.class)) {
			Path parent = Paths.get(localClassPath(clazz,path));
			try {
				p.load(Files.newInputStream(Paths.get(parent.toString()+File.separator+mvcproperties),StandardOpenOption.READ));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return p;	
	}
	
	public static String getContextProperties(Class<?> clazz) {
		return loadPropertiesResource(clazz).getProperty(webcontext);
	}
}
